<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 达达 <ccbox_net@163.com>
// +----------------------------------------------------------------------
namespace app\goods\model;

use app\admin\model\RouteModel;
use think\Model;

class GoodsModel extends Model
{
    /**
     * 商品模型
     * @var string
     */
    protected $name = 'goods';

    protected $type = [
        'more' => 'array',
    ];

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 关联分类表
     * @return \think\model\relation\BelongsToMany
     */
    public function categories()
    {
        return $this->belongsToMany('GoodsCategoryModel', 'goods_category_map', 'category_id', 'goods_id');
    }

    /**
     * 关联品牌表
     * @return \think\model\relation\BelongsTo
     */
    public function brand()
    {
        return $this->belongsTo('GoodsBrandModel', 'brand_id');
    }

    /**
     * 关联标签表
     * @return \think\model\relation\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany('GoodsTagModel', 'goods_tag_map', 'tag_id', 'goods_id');
    }

    /**
     * content 字段自动转化
     * @param $value
     * @return string
     */
    public function getContentAttr($value)
    {
        if (empty($value)) {
            return '';
        }
        return cmf_replace_content_file_url(htmlspecialchars_decode($value));
    }

    /**
     * content 字段自动转化
     * @param $value
     * @return string
     */
    public function setContentAttr($value)
    {
        if (empty($value)) {
            return '';
        }
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }

    /**
     * published_time 自动完成
     * @param $value
     * @return false|int
     */
    public function setPublishedTimeAttr($value)
    {
        return strtotime($value);
    }

    /**
     * 处理资源URL
     * @param $data
     * @return $data
     */
    public function handleAsset($data)
    {
        if (!empty($data['thumbnail'])) {
            $data['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
        }

        if (!empty($data['more']['slide'])) {
            $data['more']['slide'] = cmf_asset_relative_url($data['more']['slide']);
        }

        if (!empty($data['more']['audio'])) {
            $data['more']['audio'] = cmf_asset_relative_url($data['more']['audio']);
        }

        if (!empty($data['more']['video'])) {
            $data['more']['video'] = cmf_asset_relative_url($data['more']['video']);
        }

        return $data;
    }

    /**
     * 后台管理添加商品
     * @param array        $data       商品数据
     * @param array|string $categories 商品分类 id
     * @return $this
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addGoods($data, $categories)
    {
        $data = $this->handleAsset($data);
        $this->save($data);

        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }
        $this->categories()->save($categories);

        $data['keywords'] = str_replace('，', ',', $data['keywords']);
        $keywords = explode(',', $data['keywords']);
        $this->addTags($keywords, $this->id);
        unset($data['keywords']);

        return $this;
    }

    /**
     * 后台管理编辑文章
     * @param array        $data       文章数据
     * @param array|string $categories 文章分类 id
     * @return $this
     * @throws \think\Exception
     */
    public function editGoods($data, $categories)
    {
        $data = $this->handleAsset($data);
        unset($data['categories']);
        $goods = self::find($data['id']);
        $goods->save($data);

        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }
        $oldCategoryIds = $goods->categories()->column('category_id');
        $sameCategoryIds = array_intersect($categories, $oldCategoryIds);
        $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
        $newCategoryIds = array_diff($categories, $sameCategoryIds);
        if (!empty($needDeleteCategoryIds)) {
            $goods->categories()->detach($needDeleteCategoryIds);
        }
        if (!empty($newCategoryIds)) {
            $goods->categories()->attach(array_values($newCategoryIds));
        }

        $data['keywords'] = str_replace('，', ',', $data['keywords']);
        $keywords = explode(',', $data['keywords']);
        $this->addTags($keywords, $data['id']);
        unset($data['keywords']);

        return $this;
    }

    /**
     * 增加标签
     * @param $keywords
     * @param $goodsId
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addTags($keywords, $goodsId)
    {
        $goodsTagModel = new GoodsTagModel();
        $tagIds = [];
        $data = [];

        if (!empty($keywords)) {
            $oldTagIds = GoodsTagMapModel::where('goods_id', $goodsId)->column('tag_id');

            foreach ($keywords as $keyword) {
                $keyword = trim($keyword);
                if (!empty($keyword)) {
                    $findTag = $goodsTagModel->where('title', $keyword)->find();
                    if (empty($findTag)) {
                        $tagId = $goodsTagModel->insertGetId([
                            'title' => $keyword
                        ]);
                    } else {
                        $tagId = $findTag['id'];
                    }

                    if (!in_array($tagId, $oldTagIds)) {
                        array_push($data, ['tag_id' => $tagId, 'goods_id' => $goodsId]);
                    }

                    array_push($tagIds, $tagId);
                }
            }
            // 标签为空时删除所有旧标签关系
            if (empty($tagIds) && !empty($oldTagIds)) {
                GoodsTagMapModel::where('goods_id', $goodsId)->delete();
            }

            // 不变标签
            $sameTagIds = array_intersect($oldTagIds, $tagIds);
            $shouldDeleteTagIds = array_diff($oldTagIds, $sameTagIds);
            if (!empty($shouldDeleteTagIds)) {
                GoodsTagMapModel::where('goods_id', $goodsId)
                    ->where('tag_id', 'in', $shouldDeleteTagIds)
                    ->delete();
            }

            if (!empty($data)) {
                GoodsTagMapModel::insertAll($data);
            }
        } else {
            GoodsTagMapModel::where('goods_id', $goodsId)->delete();
        }
    }
}